//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package desccmd

import (
	"encoding/json"
	"fmt"
	"os"

	"github.com/spf13/cobra"
	"google.golang.org/protobuf/proto"
	"google.golang.org/protobuf/types/descriptorpb"
)

var inputFile = ""

var DescCommand = &cobra.Command{
	Use: "desc",
	RunE: func(cmd *cobra.Command, args []string) error {
		return runDescCommand()
	},
}

func runDescCommand() error {
	data, err := os.ReadFile(inputFile)
	if err != nil {
		return err
	}
	descSet := &descriptorpb.FileDescriptorSet{}
	err = proto.Unmarshal(data, descSet)
	if err != nil {
		return err
	}
	svcInfoList := []*ServiceInfo{}
	for _, fd := range descSet.File {
		svcList := fd.GetService()
		if len(svcList) == 0 {
			continue
		}
		pkgName := fd.GetPackage()
		for _, svc := range svcList {
			svcInfo := &ServiceInfo{
				MethodList: []MethodInfo{},
			}
			svcInfo.ServiceName = pkgName + "." + svc.GetName()
			methodList := svc.GetMethod()
			for _, method := range methodList {
				svcInfo.MethodList = append(svcInfo.MethodList, MethodInfo{
					MethodName:   method.GetName(),
					ClientStream: method.GetClientStreaming(),
					ServerStream: method.GetServerStreaming(),
				})
			}
			svcInfoList = append(svcInfoList, svcInfo)
		}
	}
	jsonData, err := json.Marshal(svcInfoList)
	if err != nil {
		return err
	}
	fmt.Println(string(jsonData))
	return nil
}

func init() {
	DescCommand.Flags().StringVar(&inputFile, "in", "", "proto parse info file")
}
